package com.angel.core;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.angel.core.util.JsonUtil;
import com.angel.core.util.StringUtils;
import com.angel.health.SysLogWithBLOBs;
import com.angel.provider.sys.SysManagerLogProvider;


/**
 * @author 程千万
 * 2016-7-29
 */
public class CommonInterceptor extends HandlerInterceptorAdapter{
	
	public static final String LAST_PAGE = "";
	public String[] allowUrls;//还没发现可以直接配置不拦截的资源，所以在代码里面来排除 
	public void setAllowUrls(String[] allowUrls) {   
		this.allowUrls = allowUrls;   
	} 
	@Autowired
	private SysManagerLogProvider provider;
    /** 
     * 在业务处理器处理请求之前被调用 
     * 如果返回false 
     *     从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
     * 如果返回true 
     *    执行下一个拦截器,直到所有的拦截器都执行完毕 
     *    再执行被拦截的Controller 
     *    然后进入拦截器链, 
     *    从最后一个拦截器往回执行所有的postHandle() 
     *    接着再从最后一个拦截器往回执行所有的afterCompletion() 
     */  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
    	String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
    	String userid =  (String)request.getSession().getAttribute("user"); 
    	
    	
    	
    	if(null != allowUrls && allowUrls.length>=1){   
    		for(String url : allowUrls) {     
    			if(requestUrl.contains(url)) {     
    		         	return true;     
    		    }     
    		}
    	}
    	
    	if(requestUrl.contains("/app/")){
    		SysLogWithBLOBs log = getLog(request, requestUrl);
    		provider.save(log);
    		return true;
    	}
    	if(userid == null){
    		request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
    		return false;
    	}else{
    		SysLogWithBLOBs log = getLog(request, requestUrl);
    		provider.save(log);
    		return true;
    	}
    }  
  
    /**
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作   
     * 可在modelAndView中加入数据，比如当前时间
     */
    @Override  
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler,  
            ModelAndView modelAndView) throws Exception {   
//        log.info("==============执行顺序: 2、postHandle================");  
        if(modelAndView != null){  //加入当前时间  
            //modelAndView.addObject("var", "测试postHandle");  
        }  
    }  
  
    /** 
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等  
     *  
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion() 
     */  
    @Override  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex)  
            throws Exception {  
//        log.info("==============执行顺序: 3、afterCompletion================");  
    }  
    
  //获取ip
  	public static String getIpAddr(HttpServletRequest request) {
          String ip = request.getHeader("X-Real-IP");
          if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
              return ip;
          }
          ip = request.getHeader("X-Forwarded-For");
          if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
          // 多次反向代理后会有多个IP值，第一个为真实IP。
          int index = ip.indexOf(',');
              if (index != -1) {
                  return ip.substring(0, index);
              } else {
                  return ip;
              }
          } else {
               return request.getRemoteAddr();
          }
      }
  	
  	//获取主机名
  	public static String getHostName(String ip){  
          InetAddress inet;  
          try {  
              inet = InetAddress.getByName(ip);  
              return inet.getHostName();  
          } catch (UnknownHostException e) {  
              e.printStackTrace();  
          }  
          return "";  
      } 
  	//记录日志
  	public static SysLogWithBLOBs getLog(HttpServletRequest request,String requestUrl){
  		SysLogWithBLOBs log = new SysLogWithBLOBs();
  		String loginInfo = (String) request.getSession().getAttribute("user");
		String userName;
		if (loginInfo != null && !"".equals(loginInfo)) {
			userName = loginInfo;
		} else {
			userName = "用户未登录";
		}
		log.setCreateBy(userName);
		log.setCreateTime(new Date());
		String ip = getIpAddr(request);;
		log.setRemoteAddr(ip );
		log.setHostName(getHostName(ip));
		log.setMethod(request.getMethod());
		log.setRequestUri(request.getRequestURI());
		String logType = "";
		if(!StringUtils.isEmpty(requestUrl)){
			if(requestUrl.startsWith("/app/")){
				logType = "1";
			}else{
				logType = "0";
			}
		}
		log.setType(logType);
		log.setParams(JsonUtil.toJson(request.getParameterMap()));
		return log;
  	}
}  